/*
 * UpdateProfileServlet.java
 * 作用：处理用户修改个人信息（如用户名、手机号、头像）的请求，包括文件上传。
 */
package com.campustradingwall.controller.user;

import com.campustradingwall.dao.UserDao;
import com.campustradingwall.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

@WebServlet("/user/updateProfile")
@MultipartConfig
public class UpdateProfileServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("user");

        // 更新用户名和手机
        user.setUsername(request.getParameter("username"));
        user.setPhone(request.getParameter("phone"));

        // 处理文件上传
        Part filePart = request.getPart("avatar");
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();

        if (fileName != null && !fileName.isEmpty()) {
            // 设置一个唯一的文件名以避免冲突
            String uniqueFileName = user.getId() + "_" + System.currentTimeMillis() + "_" + fileName;
            String uploadPath = getServletContext().getRealPath("") + File.separator + "uploads" + File.separator + "avatars";
            
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            filePart.write(uploadPath + File.separator + uniqueFileName);
            user.setAvatar(uniqueFileName);
        }

        // 将更新后的用户信息保存到数据库
        // 注意：这里只更新了部分字段，如果UserDao的updateUser方法更新所有字段，需要先获取完整的user对象
        userDao.updateUser(user);
        
        request.getSession().setAttribute("message", "个人信息更新成功！");
        response.sendRedirect(request.getContextPath() + "/user/profile");
    }
} 